package StudyCode.summary.csv;

import java.io.Reader;
import java.util.List;
import java.util.Vector;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class ParseCSVLineFromReader {
	public static List<String> parseLine(Reader r) throws Exception {
		int ch = r.read();
		while (ch == '\r') {
			ch = r.read();
		}
		if (ch < 0) {
			return null;
		}
		Vector<String> store = new Vector<String>();
		StringBuffer curVal = new StringBuffer();
		boolean inquotes = false;
		boolean started = false;
		while (ch >= 0) {
			if (inquotes) {
				started = true;
				if (ch == '\"') {
					inquotes = false;
				} else {
					curVal.append((char) ch);
				}
			} else {
				if (ch == '\"') {
					inquotes = true;
					if (started) {
						curVal.append('\"');
					}
				} else if (ch == ',') {
					store.add(curVal.toString());
					curVal = new StringBuffer();
					started = false;
				} else if (ch == '\r') {

				} else if (ch == '\n') {

					break;
				} else {
					curVal.append((char) ch);
				}
			}
			ch = r.read();
		}
		store.add(curVal.toString());
		return store;
	}

	public static List<String> parseLine(Reader r, boolean t)
			throws Exception {
		int ch = r.read();
		if (ch < 0) {
			return null;
		}
		Vector<String> store = new Vector<String>();
		StringBuffer curVal = new StringBuffer();
		while (ch != '\r') {
			if (ch == 32 || ch == '\r' || ch == '\n') {
				ch = r.read();
				continue;
			} else if (ch < 0) {
				return null;
			} else if ((char) ch != ',') {
				curVal.append((char) ch);
			} else if (ch == ',') {
				store.add(curVal.toString());
				curVal = new StringBuffer();
			} else if (ch == '\n') {
				break;
			} else {
				curVal.append((char) ch);
			}
			ch = r.read();
		}

		store.add(curVal.toString());

		return store;
	}
}
